package greaderbook.backend;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

/**
 * Class for sending username and password to Google to retrieve SID for Google Reader API.
 * @author Jia Cherng Ho
 *
 */
public class AuthenticationRequest {
	private static final String login_url = "https://www.google.com/accounts/ClientLogin";
	private HttpClient httpclient;
	private HttpPost httppost;
	private List<NameValuePair> postParams;
	private BasicNameValuePair userValue;
	private BasicNameValuePair passValue;
	private boolean first;
	
	/**
	 * AuthenticationRequest constructor.
	 */
	public AuthenticationRequest() {
		httpclient = new DefaultHttpClient();
		httppost = new HttpPost(login_url);
		postParams = new ArrayList<NameValuePair>(5);
		postParams.add(new BasicNameValuePair("service", "reader"));
		postParams.add(new BasicNameValuePair("source", "GreaderBook"));
		postParams.add(new BasicNameValuePair("continue",
				"http://www.google.com/"));
		first = true;
	}
	
	/** 
	 * Send post parameters to login_url for a response,  
	 * if credentials are correct response contains SID, LSID etc, 
	 * else response is Error=BadAuthentication. 
	 * @param user	gmail username
	 * @param pass	gmail password 
	 * @return		SID string if credentials are correct
	 */
	public String getSID(String user, String pass) throws ClientProtocolException, IOException {
		if (first) {
			first = false;
		} else {
			postParams.remove(userValue);
			postParams.remove(passValue);
		}
		userValue = new BasicNameValuePair("Email", user);
		passValue = new BasicNameValuePair("Passwd", pass);
		postParams.add(userValue);
		postParams.add(passValue);
		httppost.setEntity(new UrlEncodedFormEntity(postParams));
		HttpResponse resp = httpclient.execute(httppost);
		int respLength = (int) resp.getEntity().getContentLength();
		byte[] byteResp = new byte[respLength];
		resp.getEntity().getContent().read(byteResp,0,respLength);
		String respString = new String(byteResp);
		int endIndex = respString.indexOf("LSID");
		if (endIndex != -1)
			return respString.substring(4, endIndex);
		return null;
	}
}
